#include "led.h" 
#include "rtc.h"
#include "hal_ucs.h"
#include "uart.h"
#include "handl.h"

volatile unsigned char time = 0x00;

volatile Calendar newTime;

void main (void)
{
//    Calendar currentTime;
	
	//Stop WDT
    WDTCTL = WDTPW + WDTHOLD;               // Stop watchdog timer.
	
	UART_config();
    LED_config();
    
	print("hello world\n");

    P5SEL |= BIT4 + BIT5;                       // Port select XT1
    
	//Initialize clock and peripherals
	LFXT_Start(XT1DRIVE_3, XCAP_3);
    Init_FLL_Settle(8000, 244);
    SFRIE1 |= OFIE;
	setupRTC(); 


	print("come here!");

    //Enter LPM3 mode with interrupts enabled
    //Enter LPM3 mode with interrupts enabled
    __bis_SR_register(GIE);
    
    while (1) {
        if (time == 0x01) {
            time = 0x00;
            LED1_toggle();
            print_char(hextodec(newTime.Hours) / 10 + 48);
            print_char(hextodec(newTime.Hours) % 10 + 48);
            print_char(':');
            print_char(hextodec(newTime.Minutes) / 10 + 48);
            print_char(hextodec(newTime.Minutes) % 10 + 48);
            print_char(':');
            
            print_char(hextodec(newTime.Seconds) / 10 + 48);
            print_char(hextodec(newTime.Seconds) % 10 + 48);    
            
            print_char('\n');
        }
    }
}

#pragma vector=RTC_VECTOR
__interrupt void RTC_ISR (void)
{
//    newTime = RTC_getCalendarTime(__MSP430_BASEADDRESS_RTC__);
	newTime = rtc_getCalendarTime();

    switch (__even_in_range(RTCIV,16)){
        case 0: break;  //No interrupts
        case 2:         //RTCRDYIFG
            //Toggle P1.0 every second
            time = 0x01; 
            
            break;
        case 4:         //RTCEVIFG
            //Interrupts every minute
            
            //Read out New Time a Minute Later BREAKPOINT HERE 


            break;
        case 6:         //RTCAIFG
            //Interrupts 5:00pm on 5th day of week
            __no_operation();
            break;
        case 8: break;  //RT0PSIFG
        case 10: break; //RT1PSIFG
        case 12: break; //Reserved
        case 14: break; //Reserved
        case 16: break; //Reserved
        default: break;
    }
}

#pragma vector=UNMI_VECTOR
__interrupt void UNMI_ISR(void)
{
    switch (SYSUNIV)
    {
        case 0x0004:  LFXT_Start(XT1DRIVE_3, XCAP_3); break;
        default: break;
    }
}
